package com.googlecode.vanaraha.utils

object FileUtils {
   import java.io.{InputStream, FileInputStream, BufferedInputStream, BufferedReader, FileReader}

   implicit def str2readAll(path: String)= new {
     val maxLength = 1024
     def readAll: String = {
       val buffer = new StringBuffer
       safeFileRead(path){ in: BufferedReader =>
    	   val byteArr = new Array[Char](maxLength)
    	   var bytesRead = 0
    	   while({bytesRead = in.read(byteArr, 0, maxLength); bytesRead != -1}){
    	     buffer.append(byteArr, 0, bytesRead)
    	   }
       }
       buffer toString
     }
   }
   
   def safeFileRead(path: String)(fileOperation: BufferedReader => Unit){
     safeOperation[BufferedReader]({createBufferedReader(path)})(fileOperation)
   }
   
   def safeOperation[A <% {def close():Unit}](streamCreator: => A)(fileOperation: A => Unit){
     var in: A = null.asInstanceOf[A]
     try{
       in = streamCreator
       fileOperation(in)
     }finally{
       if(in!=null)
         in.close
     }
   }   
   
   def createBufferedInStream(path: String) = new BufferedInputStream(new FileInputStream(path))
   def createBufferedReader(path: String) =  new BufferedReader(new FileReader(path))
   
}
